package uk.co.cocking.getinline2.pipeline.transformers;

import java.util.List;

import uk.co.cocking.getinline2.pipeline.io.CouldNotProcessRecordException;
import uk.co.cocking.getinline2.record.MapRecord;
import uk.co.cocking.getinline2.record.Record;
import uk.co.cocking.getinline2.record.TagField;
import uk.co.cocking.getinline2.tagging.TaggingRule;

public class Tagger extends AbstractTransformer<Record, Record> {
	
	private final TaggingRule[] rules;
	private final String tagFieldName;

	public Tagger(String tagFieldName, TaggingRule...rules) {
		this.tagFieldName = tagFieldName;
		this.rules = rules;
	}

	@Override
	public List<Record> transform(Record incomingRecord)
			throws CouldNotProcessRecordException {
		TagField tagField;
			Record outgoingRecord = addTagFieldIfMissingFrom(incomingRecord);
		for (TaggingRule rule: rules) {
			tagField = (TagField) outgoingRecord.getField(tagFieldName);
			tagField.addTags(rule.getTagsFor(incomingRecord));
		}
		return enlist(outgoingRecord);
	}

	private Record addTagFieldIfMissingFrom(Record incomingRecord) throws CouldNotProcessRecordException {
		if (!incomingRecord.hasField(tagFieldName)) {
			return new MapRecord(incomingRecord, new TagField(tagFieldName));
		}
		if (incomingRecord.getField(tagFieldName) instanceof TagField) {
			return incomingRecord;
		}
		throw new CouldNotProcessRecordException("field "+tagFieldName+" is not a tag field in "+incomingRecord);
	}

}
